package com.zl.learning.db.redis;

import org.junit.Test;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class RedisManager {

//    private static JedisPool jedisPool = new JedisPool("172.31.4.248", 6379);
    private static JedisPool jedisPool = new JedisPool("127.0.0.1", 6379);

    private static Map<Integer, Boolean> dbUseMap = new ConcurrentHashMap<>();

    static {
        for (int i = 1; i <= 15; i++) {
            dbUseMap.put(i, true);
        }
    }

    public Jedis getJedis() {
        return jedisPool.getResource();
    }

    public synchronized Integer getDbIndex() {
        for (int i = 1; i <= 15; i++) {
            if (dbUseMap.get(i)) {
                dbUseMap.put(i, false);
                return i;
            }
        }
        return null;
    }

    public synchronized void close(Jedis jedis, Integer dbIndex) {
        dbUseMap.put(dbIndex, true);
        jedis.flushDB();
        jedis.close();
    }

    @Test
    public void test1() {
        for (int i = 0; i < 17; i++) {
            Integer dbIndex = getDbIndex();
            System.out.println(dbIndex);
            if (dbIndex % 3 == 0) {
                Jedis jedis = jedisPool.getResource();
                jedis.select(dbIndex);
                close(jedis,dbIndex);
            }
        }
    }

    @Test
    public void test2(){
        System.out.println(dbUseMap);
    }

    @Test
    public void test3() {
        try (Jedis resource = jedisPool.getResource()){
//            resource.set("aaaa","aaaaa");
            System.out.println(resource.get("aaaa"));
        }
    }
}
